import fs from 'fs';
import path from 'path'
import _ from 'lodash'
import config from '../config/globalConfig';

export function installModel(name) {
    const models = {};
    let fileObj = mapDir(path.join(__dirname));
    Object.keys(fileObj).forEach((keyName) => {
        let keyItem = fileObj[keyName];
        if (config.dirNameList.indexOf(keyName) > -1) {
            Object.keys(keyItem).forEach(childKeyName => {
                let fileName = childKeyName + ".js";//文件名称
                let filePath=path.join(__dirname + "/" + keyName + "/", fileName);
                const model = require(filePath);
                models[childKeyName] = model;
            })
        } else {
            let fileName = keyName + ".js";//文件名称
            const model = require(path.join(__dirname, fileName));
            models[keyName] = model;
        }
    });

    Object.keys(models).forEach((modelName) => {
        if (models[modelName].associate) {
            models[modelName].associate(models);
        }
    });
    if (name === undefined || name.length === 0 || name === null)
        return models;
    else
        return models[name];
};

/**
 * 遍历指定目录下所有的文件
 * @param d
 */
const mapDir = d => {
    let fileObj = {};
    // 获得当前文件夹下的所有的文件夹和文件
    const [dirs, files] = _(fs.readdirSync(d)).partition(p => fs.statSync(path.join(d, p)).isDirectory());
    // 映射文件夹
    dirs.forEach(dir => {
        fileObj[dir] = mapDir(path.join(d, dir))
    });
    // 映射文件
    files.forEach(file => {
        if (path.extname(file) === '.js' && file !== 'index.js' && file !== 'base.js') {
            fileObj[path.basename(file, '.js')] = {};
        }
    });
    return fileObj
};
